//获取应用实例
var app = getApp()
var common = require('../../template/getCode.js')
var Bmob = require('../../../utils/Bmob-1.6.5.min.js');
var that;
var myDate = new Date();
//格式化日期
function formate_data(myDate) {
  let month_add = myDate.getMonth() + 1;
  var formate_result = myDate.getFullYear() + '-' +
    month_add + '-' +
    myDate.getDate()
  return formate_result;
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    notice_status: false,
    accounts: ["微信号", "QQ号", "手机号"],
    accountIndex: 0,
    peopleHide: false,
    isAgree: false,
    date: formate_data(myDate),
    address: '点击选择位置',
    longitude: 0, //经度
    latitude: 0, //纬度
    customerLongitude: 0, //经度
    customerLatitude: 0, //纬度
    showTopTips: false,
    TopTips: '',
    noteMaxLen: 200, //备注最多字数
    content: "",
    noteNowLen: 0, //备注当前字数
    types: ["运动", "游戏", "交友", "旅行", "读书", "竞赛", "电影", "音乐", "其他"],
    typeIndex: "0",
    showInput: false, //显示输入真实姓名,
    // user_address: "游戏",
    // user_name: "游戏",
    // user_phone: "13111111111",
    // product_name: "a",
     user_address: "",
    user_name: "",
    user_phone: "",
    product_name: "",
    weight_gram: 1,
    openid: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  tapNotice: function(e) {
    if (e.target.id == 'notice') {
      this.hideNotice();
    }
  },
  showNotice: function(e) {
    this.setData({
      'notice_status': true
    });
  },
  hideNotice: function(e) {
    this.setData({
      'notice_status': false
    });
  },


  //字数改变触发事件
  bindTextAreaChange: function(e) {
    var that = this
    var value = e.detail.value,
      len = parseInt(value.length);
    if (len > that.data.noteMaxLen)
      return;
    that.setData({
      content: value,
      noteNowLen: len
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;

    that.setData({ //初始化数据
      src: "",
      isSrc: false,
      ishide: "0",
      autoFocus: true,
      isLoading: false,
      loading: true,
      isdisabled: false,
      openid: wx.getStorageSync('user_openid')
    })
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.hideToast()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    //var myInterval = setInterval(getReturn, 500); ////半秒定时查询
    function getReturn() {

      wx.getStorage({
        key: 'user_openid',
        success: function(ress) {
          if (ress.data) {
            clearInterval(myInterval)
            that.setData({
              loading: true
            })
          }
        }
      })

    }
  },


  //表单验证
  showTopTips: function() {
    var that = this;
    this.setData({
      showTopTips: true
    });
    setTimeout(function() {
      that.setData({
        showTopTips: false
      });
    }, 3000);
  },
  //选择地点
  addressChange: function(e) {
    this.addressChoose(e);
  },
  addressChoose: function(e) {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        that.setData({
          user_address: res.address,
          longitude: res.longitude, //经度
          latitude: res.latitude, //纬度
        })
        if (e.detail && e.detail.value) {
          this.data.user_address = res.address;
        }
      },
      fail: function(e) {},
      complete: function(e) {}
    })
  },
  //提交表单
  submitForm: function(e) {
    var that = this;
    console.log(wx.getStorageSync('user_openid'));

    var user_name = e.detail.value.user_name;
    var user_phone = e.detail.value.user_phone;
    var user_address = e.detail.value.user_address;
    var product_name = e.detail.value.product_name;
    var weight_gram = e.detail.value.weight_gram;
    var longitude = that.data.longitude; //经度 
    var latitude = that.data.latitude; //纬度

    var customerLatitude = app.globalData.userLocation.latitude; //客户所在纬度
    var customerLongitude = app.globalData.userLocation.longitude; //客户所在经度

    var phReg = /^1[34578]\d{9}$/;
    var nameReg = new RegExp("^[\u4e00-\u9fa5]{2,4}$");
    //先进行表单非空验证
    if (user_name == "") {
      this.setData({
        showTopTips: true,
        TopTips: '请输入收件人'
      });
    } else if (user_name != "" && !nameReg.test(user_name)) {
      this.setData({
        showTopTips: true,
        TopTips: '姓名一般为2-4位汉字'
      });
    } else if (user_phone == "") {
      this.setData({
        showTopTips: true,
        TopTips: '请输入联系方式'
      });
    } else if (!phReg.test(user_phone)) {
      this.setData({
        showTopTips: true,
        TopTips: '手机号格式不正确'
      });
    } else if (user_address == '') {
      this.setData({
        showTopTips: true,
        TopTips: '请输入地址'
      });
    } else if (product_name == '') {
      this.setData({
        showTopTips: true,
        TopTips: '请输入寄托物品'
      });
    } else if (weight_gram == '') {
      this.setData({
        showTopTips: true,
        TopTips: '请输入物品重量'
      });
    } else {
      console.log('校验完毕');
      that.setData({
        isLoading: true,
        isdisabled: true
      })


      //创建类和实例
      const diary = Bmob.Query("orders");

      diary.set("ProductName", product_name);
      diary.set("WeightGram", weight_gram);
      diary.set("ReceiveName", user_name);
      diary.set("ReceiveMobile", user_phone);
      diary.set("ReceiveAddress", user_address);
      diary.set("OpenId", wx.getStorageSync("user_openid"));
      diary.set("ReceiveLatitude", latitude);
      diary.set("ReceiveLongitude", longitude);
      diary.set("CustomerLatitude", customerLatitude);
      diary.set("CustomerLongitude", customerLongitude);
      diary.set("Status", 0);
      //添加数据，第一个入口参数是null
      diary.save().then(res => {
        console.log(res)
        common.dataLoading(" 成功", "success", function() {
          that.setData({
            isLoading: false,
            isdisabled: false
          })

        });

      }).catch(err => {
        console.log(err)
        that.setData({
          isLoading: false,
          isdisabled: false
        })
      })



    }
    setTimeout(function() {
      that.setData({
        showTopTips: false
      });
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})